//
//  ReportReasonViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/14.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "CommonReportReasonModel.h"

#import "ReportReasonCell.h"
#import "ReportReasonFooterView.h"
#import "ReportReasonHeaderView.h"

#import "ReportReasonViewController.h"

@interface ReportReasonViewController ()<UITableViewDelegate, UITableViewDataSource, UITextViewDelegate>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) NSMutableArray <CommonReportReasonModel *>*dataArray;

@property (nonatomic, strong) NSMutableArray *data;

@property (nonatomic, strong) ReportReasonFooterView *inputFooter;

@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation ReportReasonViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self prepareData];
    [self initView];
}

- (void)prepareData {
    
    self.dataArray = @[].mutableCopy;
    for (NSDictionary *dic in self.data) {
        CommonReportReasonModel *model = [CommonReportReasonModel modelWithDictionary:dic];
        [self.dataArray addObject:model];
    }
}

- (void)initView {
    
    self.title = @"举报";
    self.selectIndex = 0;
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    UIButton *publishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    publishBtn.frame = CGRectMake(0,0,52,24);
    publishBtn.layer.cornerRadius = 12.0f;
    [publishBtn setBackgroundColor:UIColorHex(0xFF4242)];
    publishBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [publishBtn setTitle:@"提交" forState:UIControlStateNormal];
    [publishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [publishBtn addTarget:self action:@selector(publishAction) forControlEvents:UIControlEventTouchUpInside];
    
    [publishBtn.widthAnchor constraintEqualToConstant:52].active =YES;
    [publishBtn.heightAnchor constraintEqualToConstant:24].active =YES; 
    
    UIBarButtonItem *publishItem = [[UIBarButtonItem alloc] initWithCustomView:publishBtn];

    self.navigationItem.rightBarButtonItems =@[publishItem];
    
    [self.tableview reloadData];
}

//仿placeholder
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@"为帮助审核人员更快速处理，请您详细描述举报理由"]) {
        textView.textColor = UIColorHex(0x333333);
        textView.text = @"";
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@""]) {
        textView.textColor = UIColorHex(0xbbbbbb);
        textView.text = @"为帮助审核人员更快速处理，请您详细描述举报理由";
    }
    
    self.inputFooter.countLab.text = [NSString stringWithFormat:@"%lu/50",(unsigned long)textView.text.length];

    return YES;
}

- (void)publishAction {
    
    if (self.selectIndex == self.dataArray.count -1) {
        
        if (self.inputFooter.contentTV.text.length > 0 && ![self.inputFooter.contentTV.text isEqualToString:@"为帮助审核人员更快速处理，请您详细描述举报理由"]) {
            
            if (self.inputFooter.contentTV.text.length>50) {
                
                [SVProgressHUD showErrorWithStatus:@"举报理由最多为50字"];
                [SVProgressHUD dismissWithDelay:1];
                
            } else {
                [self request_report];
            }
            
            
        } else {
            [SVProgressHUD showErrorWithStatus:@"请填写原因"];
            [SVProgressHUD dismissWithDelay:1];
        }
    } else {
        [self request_report];
    }
    
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 47;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ReportReasonHeaderView *header = [[NSBundle mainBundle] loadNibNamed:@"ReportReasonHeaderView" owner:nil options:nil].firstObject;
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    self.inputFooter = [[NSBundle mainBundle] loadNibNamed:@"ReportReasonFooterView" owner:nil options:nil].firstObject;
    self.inputFooter.contentTV.delegate = self;
    [RACObserve(self.inputFooter.contentTV, text) subscribeNext:^(id x) {

        self.dataArray.lastObject.content = self.inputFooter.contentTV.text;
        
        self.inputFooter.countLab.text = [NSString stringWithFormat:@"%lu/50",(unsigned long)self.inputFooter.contentTV.text.length];
        
        if (self.inputFooter.contentTV.text.length > 50) {
            self.inputFooter.countLab.textColor = UIColorHex(0xff4242);
        } else {
            self.inputFooter.countLab.textColor = UIColorHex(0x999999);
        }
    }];
    
    return self.inputFooter;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    if (self.dataArray[self.selectIndex].hasExt) {
        return 140;
    } else {
        return CGFLOAT_MIN;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ReportReasonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReportReasonCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    
    cell.mainTitleLab.text = self.dataArray[indexPath.row].title;
    if (self.dataArray[indexPath.row].isSelect) {
        [cell.selIcon setImage:[UIImage imageNamed:@"common_sel"]];
    } else {
        [cell.selIcon setImage:[UIImage imageNamed:@"common_nor"]];

    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    for (CommonReportReasonModel *model in self.dataArray) {
        model.isSelect = NO;
    }
    self.dataArray[indexPath.row].isSelect = YES;
    self.selectIndex = indexPath.row;
    [self.tableview reloadData];
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xffffff);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"ReportReasonCell" bundle:nil] forCellReuseIdentifier:@"ReportReasonCellID"];
    }
    return _tableview;
}


-(NSMutableArray<CommonReportReasonModel *> *)dataArray {
    
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (NSMutableArray *)data {
    NSArray *data = @[
        @{@"isSelect": @(1),
          @"title":@"虚假内容",
          @"content":@"",
          @"hasExt":@(0)
        },
        @{@"isSelect": @(0),
          @"title":@"色情暴力",
          @"content":@"",
          @"hasExt":@(0)
        },
        @{@"isSelect": @(0),
          @"title":@"全部广告",
          @"content":@"",
          @"hasExt":@(0)
        },
        @{@"isSelect": @(0),
          @"title":@"内容与主题不符",
          @"content":@"",
          @"hasExt":@(0)
        },
        @{@"isSelect": @(0),
          @"title":@"其他",
          @"content":@"",
          @"hasExt":@(1)
        },
    ];
    return data.mutableCopy;
}

//API_AddReport
- (void)request_report {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:self.baseId forKey:@"baseId"];//举报内容
    [dic setValue:self.dataArray[self.selectIndex].title forKey:@"reason"];//举报内容
    [dic setValue:self.inputFooter.contentTV.text forKey:@"remark"];//备注
    
    [dic setValue:@"2" forKey:@"source"];//（1：平台，2：用户，3：商家）
    [dic setValue:self.level forKey:@"level"];//（）

    //（1：帖子，2：帖子-评论，3：帖子-回复，4：问题，5：话题-评论，6：话题-回复，7-问题-答案
    [dic setValue:@(self.type) forKey:@"type"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];//备注

    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_AddReport];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
                
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                                
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {
        

    }];
}

@end
